package com.hanbang.mrcm.application;

import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONException;
import org.json.JSONObject;
import cn.sharesdk.framework.ShareSDK;
import com.hanbang.mrcm.R;
import com.hanbang.mrcm.base.BaseActivity;
import com.hanbang.mrcm.bean.UserInforData;
import com.hanbang.mrcm.home.HomeActivity;
import com.hanbang.mrcm.utils.HttpInterfaces;
import com.hanbang.mrcm.utils.JsonHelper;
import com.hanbang.mrcm.utils.MyLog;
import com.hanbang.mrcm.utils.MyRequestCallBack;
import com.hanbang.mrcm.utils.MySharedPreferences;
import com.hanbang.mrcm.utils.MyToast;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.testin.agent.TestinAgent;
import com.testin.agent.TestinAgentConfig;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

public class WelcomeActivity extends BaseActivity {
	private int time = 3000;
	private Timer timer = new Timer();
	private boolean isToNext = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ImageView imageView = new ImageView(this);
		imageView.setScaleType(ScaleType.CENTER_CROP);
		imageView.setImageResource(R.drawable.lead);
		setContentView(imageView);
		next();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				while (isToNext) {
					myHandler.sendEmptyMessage(0x123);
					break;
				}

			}
		}, time);
	}

	Handler myHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0x123) {
				timer.cancel();
				Intent intent = new Intent();
				intent.setClass(WelcomeActivity.this, HomeActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				finish();
			}
		};
	};

	private void next() {
		String userInfo = userData == null ? "no_login" : userData.getMobile();
		// 云测
		TestinAgentConfig config = new TestinAgentConfig.Builder(this)
				.withAppKey("c920674") // Appkey of
										// your
										// appliation,
										// required
				.withAppChannel(null) // Channel of your application
				.withUserInfo(userInfo) // User infomation like login account of
										// user
				.withDebugModel(false) // Output the crash log in local if you
										// open debug mode
				.withErrorActivity(true) // Output the activity info in crash or
											// error log
				.withCollectNDKCrash(true) // Collect NDK crash or not if you
											// use our NDK
				.withOpenCrash(true) // Monitor crash if true
				.withReportOnlyWifi(false) // Report data only on wifi mode
				.withReportOnBack(true) // allow to report data when application
										// in background
				.build();
		TestinAgent.init(config);
		new Thread() {
			public void run() {
				try {
					ShareSDK.initSDK(getApplicationContext());
				} catch (Exception e) {
				}

			};
		}.start();
		if (isLogin(false)) {
			// 检查密码的正确性
			verifyLogin();
		} else {
			// 未登录
			isToNext = true;
		}

	}

	/*
	 * 如果已经保存密码 那么就检查此密码的正确性
	 */
	private void verifyLogin() {

		RequestParams params = new RequestParams();
		params.addBodyParameter("action", "user_login");
		params.addBodyParameter("mobile", userData.getMobile());
		params.addBodyParameter("password", userData.getPassword());
		httpUtils.send(HttpMethod.POST, HttpInterfaces.userLogin, params,
				new MyRequestCallBack<String>(this, null) {
					@Override
					public void onFailure(HttpException error, String msg) {
						super.onFailure(error, msg);
						isToNext = true;
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								UserInforData userInforData = JsonHelper
										.parseObject(json, UserInforData.class);
								try {
									dbUtils.saveOrUpdate(userInforData);
									// 把id 保存在sp
									MySharedPreferences
											.setSharedPreferencesKeyAndValue(
													WelcomeActivity.this,
													MySharedPreferences.USER_DATA,
													"user_id",
													userInforData.getId());
									MyLog.e("login", "id保存成功");
									isToNext = true;
								} catch (DbException e) {
									e.printStackTrace();
									MyLog.e("login", "id保存失败");
									MyToast.show(WelcomeActivity.this, "登录失败",
											Toast.LENGTH_SHORT);
									MySharedPreferences
											.setSharedPreferencesKeyAndValue(
													WelcomeActivity.this,
													MySharedPreferences.USER_DATA,
													"user_id", -1);
								}
							} else if (status == -100) {
								passwordIsError(true);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(WelcomeActivity.this, "登录失败",
									Toast.LENGTH_LONG);
						}
						isToNext = true;
					}
				});
	}

	@Override
	public void onBackPressed() {
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}
}
